package org.chen.aao.ai.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.speech.v1.SpeechClient;
import com.google.cloud.speech.v1.SpeechSettings;
import com.google.cloud.translate.v3.TranslationServiceClient;
import com.google.cloud.translate.v3.TranslationServiceSettings;
import com.theokanning.openai.client.OpenAiApi;
import com.theokanning.openai.service.OpenAiService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.io.FileInputStream;
import java.time.Duration;

@Slf4j
@Configuration
public class AIConfig {
    
    @Value("${ai.openai.api-key}")
    private String openAiApiKey;

    @Value("${ai.openai.url}")
    private String url;
    
    @Value("${ai.openai.timeout:60}")
    private int openAiTimeout;
    
    @Value("${ai.google.credentials-path}")
    private String googleCredentialsPath;
    
    @Bean
    public OpenAiService openAiService() {
        ObjectMapper mapper = OpenAiService.defaultObjectMapper();
        OkHttpClient client = OpenAiService.defaultClient(openAiApiKey, Duration.ofSeconds(openAiTimeout));

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(client)
                .addConverterFactory(JacksonConverterFactory.create(mapper))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        OpenAiApi api = retrofit.create(OpenAiApi.class);

        return new OpenAiService(api);
    }
    
    @Bean
    public SpeechClient speechClient() throws Exception {
        GoogleCredentials credentials = GoogleCredentials
                .fromStream(new FileInputStream(googleCredentialsPath));
        
        SpeechSettings speechSettings = SpeechSettings.newBuilder()
                .setCredentialsProvider(() -> credentials)
                .build();
        
        return SpeechClient.create(speechSettings);
    }
    
    @Bean
    public TranslationServiceClient translationServiceClient() throws Exception {
        GoogleCredentials credentials = GoogleCredentials
                .fromStream(new FileInputStream(googleCredentialsPath));
        
        TranslationServiceSettings settings = TranslationServiceSettings.newBuilder()
                .setCredentialsProvider(() -> credentials)
                .build();
        
        return TranslationServiceClient.create(settings);
    }
}